package com.laicunba.jms;

import java.math.BigDecimal;

import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonMessage {
	private JSONObject json;

	public JsonMessage(TextMessage txtMsg) {

		try {
			json = (JSONObject) new JSONParser().parse(txtMsg.getText());
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public Long getLong(String key) {
		try {
			return (Long) json.get(key);
		} catch (Exception e) {
			return null;
		}
	}

	public BigDecimal getBigDecimal(String key) {
		Object val = json.get(key);
		if (val == null) {
			return null;
		}
		if (val instanceof Double) {
			return BigDecimal.valueOf((Double) val);
		} else if (val instanceof Long) {
			return BigDecimal.valueOf((Long) val);
		} else if (val instanceof Integer) {
			return BigDecimal.valueOf((Integer) val);
		} else if (val instanceof Float) {
			return BigDecimal.valueOf((Float) val);
		}
		return null;
	}

	public Integer getInteger(String key) {
		Object val = json.get(key);
		if (val == null) {
			return null;
		}
		if (val instanceof Integer) {
			return (Integer) val;
		} else if (val instanceof Long) {
			return Integer.parseInt(Long.toString((Long) val));
		}
		return null;
	}

	public String getString(String key) { 
		return (String) json.get(key);
	}

	public boolean getBoolean(String key) {
		if(json.containsKey(key)){
			return (Boolean) json.get(key);
		}
		return false;
	}
	
	@Override
	public String toString() { 
		return json.toJSONString();
	}
}
